#include "TcpServer.hpp"
#include "Service.hpp"
#include <memory>

using namespace std;

static void Usage(std::string process)
{
    cerr << "\nUsage: " << process << " port\n" << endl;
}

int BeginHandler(Connection *conn, std::string &message, service_t service)
{
    Request req;
    if(!Parser(message, &req))
    {
        return -1;
    }

    Response resp = service(req);

    std::cout << req.x << " " << req.op << " " << req.y << std::endl;
    std::cout << resp.code << " " << resp.result << std::endl;

    std::string sendstr;
    Serialize(resp, &sendstr);

    conn->outbuffer_ += sendstr;
    conn->sender_(conn);
    if(conn->outbuffer_.empty()) conn->R_->EnableReadWrite(conn->sock_, true, false);
    else conn->R_->EnableReadWrite(conn->sock_, true, true);

    std::cout << "这里就是上次的业务逻辑啦 --- end" << std::endl;

    return 0;
}

int HandlerRequest(Connection *conn, std::string &message)
{
    return BeginHandler(conn, message, calculator);
}

int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }

    unique_ptr<TcpServer> svr(new TcpServer(HandlerRequest, atoi(argv[1])));
    svr->Run();

    return 0;
}